package com.bootadmin.controller.goods.ao.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootadmin.controller.goods.ao.CategoryAO;
import com.bootadmin.controller.goods.dto.GoodsCategorySaveRequestDTO;
import com.bootadmin.core.utils.StringUtils;
import com.bootadmin.core.web.ResultJson;
import com.bootadmin.entity.GoodsCategory;
import com.bootadmin.service.GoodsCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author kongzm
 * @description: CategoryAOImpl
 * @date 2022/7/10 16:54
 */
@Component
public class CategoryAOImpl implements CategoryAO {
    private final Logger logger = LoggerFactory.getLogger(CategoryAOImpl.class);

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Override
    public ResultJson save(HttpServletRequest request, GoodsCategorySaveRequestDTO goodsCategorySaveRequestDTO) {
        GoodsCategory goodsCategory = new GoodsCategory();
        if (goodsCategorySaveRequestDTO.getId() != null) {
            GoodsCategory cate = goodsCategoryService.getById(goodsCategorySaveRequestDTO.getId());
            goodsCategory.setVersion(cate.getVersion());
        } else {
            String level = this.createCode(goodsCategorySaveRequestDTO.getLevel());
            goodsCategorySaveRequestDTO.setLevel(level);
        }

        BeanUtils.copyProperties(goodsCategorySaveRequestDTO, goodsCategory);
        goodsCategoryService.saveOrUpdate(goodsCategory);

        return ResultJson.success("保存成功");
    }

    @Override
    public ResultJson selectList(HttpServletRequest request) {
        List<GoodsCategory> list = goodsCategoryService.list();
        return ResultJson.success(list);
    }

    // 生成code
    private String createCode(String code) {
        boolean codeIsEmpty = false;
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(code)) {
            queryWrapper.eq("LENGTH(level)", 3);
            codeIsEmpty = true;
        } else {
            queryWrapper.eq("LENGTH(level)", code.length() + 3);
            queryWrapper.likeRight("level", code);
        }

        queryWrapper.orderByDesc("id").last("limit 1");
        GoodsCategory res = goodsCategoryService.getOne(queryWrapper);
        logger.info(res==null ? "null" : JSONObject.toJSONString(res));
        if (res == null && codeIsEmpty) {
            return "001";
        } else if (res != null){
            int c = Integer.parseInt(res.getLevel().substring(res.getLevel().length() - 3)) + 1;
            return (codeIsEmpty ? "" : code) + String.format("%03d", c);
        } else {
            return code + "001";
        }
    }
}
